<template>
  <view-box ref="viewBox" body-padding-bottom="5px">
    <template v-if="!wechat">
      <group title="请输入用户信息">
        <x-input v-model="account.account" title="账号" placeholder="请输入账号">
          <i slot="label" style="padding-right:10px;display:block; font-size: 24px; color: #666;" class="iconfont icon-zhanghaoguanli"></i>
        </x-input>
         <x-input v-model="account.password" type="password" title="密码" placeholder="请输入密码">
          <i slot="label" style="padding-right:10px;display:block; font-size: 24px; color: #666;" class="iconfont icon-icon-"></i>
        </x-input>
      </group>
     <box gap="20px">
        <x-button type="primary" :disabled="(!account.password || !account.account)" @click.native="handleLoginByPassword" :show-loading="loading">登陆</x-button>
     </box>
   </template>
   <load-more v-else tip="正在登陆中..."></load-more>
  </view-box>
</template>
<script>
  import { ViewBox, XInput, Group, XButton, Box, LoadMore } from 'vux'
  import { isWechatBroswer } from '@/utils/helpers'
  export default {
    data () {
      return {
        loading: false,
        account: {
          account: null,
          password: null
        },
        wechat: isWechatBroswer()
      }
    },
    components: {
      ViewBox,
      XInput,
      Group,
      XButton,
      Box,
      LoadMore
    },
    watch: {
      '$route' (to, from) {
        if (this.$route.query.access_token) {
          this._storeToken()
        }
      }
    },
    mounted () {
      if (this.$route.query.access_token) {
        this._storeToken()
      } else {
        if (isWechatBroswer()) {
          this._wechatLogin()
        } else {
        }
      }
    },
    methods: {
      handleLoginByPassword () {
        this.loading = true
        this.$store.dispatch('loginByPassword', this.account).then(() => {
          this.loading = false
          this.$router.push({ path: '/' })
        }).catch(() => {
          this.loading = false
        })
      },
      _storeToken () {
        this.$store.commit('SET_TOKEN', this.$route.query.access_token)
        let url = localStorage.getItem('redirect') ? localStorage.getItem('redirect') : '/'
        this.$router.push(url)
      },
      _wechatLogin () {
        this.$store.commit('SET_TOKEN', '')
        let redirect = this.$route.query.redirect ? this.$route.query.redirect : '/'
        let from = localStorage.getItem('from')
        localStorage.setItem('redirect', redirect)
        window.location.href = this.$apiUrl + '/api/wechat/login?from=' + from + '&v=' + Math.random()
      }
    }
  }
</script>
<style scoped lang="less">
  
</style>